<template>
  <view class="create-container">
	<scroll-view class="scroll-area" scroll-y>
		<view class="role-container">
			<!-- 组织信息标题 -->
			<view class="section-title">组织信息</view>

			<!-- 表单内容 -->
			<view class="form-section">
			  <!-- 加油站名称 -->
			  <view class="base-form-item" :class="{ active: !formData.name&& isSubmit }">
				<view class="base-label-box">
				  <text class="label">加油站名称</text>
				  <text class="required">*</text>
				  <text class="fail-label" v-if="!formData.name && isSubmit">请填写加油站名称</text>
				</view>
				<input 
				  v-if="!isEdit"
				  class="input" 
				  type="text" 
				  v-model="formData.name" 
				  placeholder="请输入组织名称"
				  placeholder-style="color: #B5B5B5"
				/>
				<text class="input" v-else>{{formData.name}}</text>
			  </view>

			  <!-- 全称 -->
			  <view class="base-form-item" :class="{ active: !formData.fullname && isSubmit }">
				<view class="base-label-box">
				  <text class="label">全称</text>
				  <text class="required">*</text>
				  <text class="fail-label" v-if="!formData.fullname && isSubmit">请填写全称</text>
				</view>
				<input 
				  class="input" 
				  type="text" 
				  v-model="formData.fullname" 
				  placeholder="请输入组织全称"
				  placeholder-style="color: #B5B5B5"
				/>
			  </view>

			  <!-- 品牌 -->
			  <view class="base-form-item" :class="{ active: !formData.orgInfo.branch && isSubmit}">
				<view class="base-label-box">
				  <text class="label">品牌</text>
				  <text class="required">*</text>
				  <text class="fail-label" v-if="!formData.orgInfo.branch && isSubmit">请选择品牌</text>
				</view>
				<view class="picker-value" @click="openBrandPicker">
				  <text :class="{ placeholder: !formData.orgInfo.branch }">{{ formData.orgInfo.branch || '请选择' }}</text>
				  <text class="arrow">></text>
				</view>
			  </view>

			  <!-- 站长 -->
			  <view class="base-form-item" :class="{ active: !formData.director && isSubmit}">
				<view class="base-label-box">
				  <text class="label">站长</text>
				  <text class="required">*</text>
				  <text class="fail-label" v-if="!formData.director && isSubmit">请填写站长</text>
				</view>
				 <text class="name-text">{{formData.director}}</text>
			  </view>

			  <!-- 手机号 -->
			  <view class="base-form-item">
				<view class="base-label-box">
				  <text class="label">手机号</text>
				  <text class="required">*</text>
				</view>
				 <text class="phone-text">{{ formatPhone(formData.phone) }}</text>
			  </view>

			  <!-- 省市区 -->
			  <view class="base-form-item" :class="{ active: !region.text && isSubmit }">
				<view class="base-label-box">
				  <text class="label">省市区</text>
				  <text class="required">*</text>
				  <text class="fail-label" v-if="!region.text && isSubmit">请选择省市区</text>
				</view>
				<view class="picker-value" @click="openRegionPicker">
				  <text :class="{ placeholder: !region.text }">{{ region.text || '请选择' }}</text>
				  <text class="arrow">></text>
				</view>
			  </view>

			  <!-- 详细地址 -->
			  <view class="base-form-item" :class="{ active: !formData.address && isSubmit }">
				<view class="base-label-box">
				  <text class="label">详细地址</text>
				  <text class="required">*</text>
				  <text class="fail-label" v-if="!formData.address && isSubmit">请填写详细地址</text>
				</view>
				<input 
				  class="input" 
				  type="text" 
				  v-model="formData.address" 
				  placeholder="请输入详细地址"
				  placeholder-style="color: #B5B5B5"
				/>
			  </view>
			</view>
		</view>
    </scroll-view>
  
    <!-- 提交按钮 -->
    <view class="button-section">
      <button class="gvr-yellow-button surebutton" @click="handleSubmit">提交</button>
    </view>

    <!-- 品牌选择器 -->
    <uni-popup ref="brandPopup" type="bottom">
      <view class="picker-content">
        <view class="picker-header">
          <text class="cancel-btn" @click="cancelBrandSelect">取消</text>
          <text class="picker-title">选择品牌</text>
          <text class="confirm-btn" @click="confirmBrandSelect">确定</text>
        </view>
        <picker-view 
          class="picker-view"
          :indicator-style="indicatorStyle"
          :value="[currentBrandIndex]"
          @change="onBrandPickerChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in brands" :key="index">
              {{ item }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>

    <!-- 使用省市区选择器组件 -->
    <region-picker 
      ref="regionPicker"
      :initial-region="region"
      @confirm="onRegionConfirm"
      @cancel="onRegionCancel"
    />

    <!-- 引入toast组件 -->
    <custom-toast ref="toastRef" :position="toastPosition"/>
	
	
  </view>
</template>

<script setup>
import { ref,onMounted, reactive } from 'vue'
import CustomToast from '@/components/custom-toast/custom-toast.vue'
import RegionPicker from '@/components/region-picker/region-picker.vue'

import { onShow } from '@dcloudio/uni-app'
import { userStore } from '@/utils/userStore.js'
import { RouterMethods,Router} from '../../utils/router'
import { USER_TYPES, orgApi, userApi } from '@/service/api'
import { formatPhone } from '@/utils/format'

const isSubmit = ref(false)
// 表单数据
const formData = ref({
  name: '',
  fullname: '',
  location: {
	  lon: 116.123, //东经为正，西经为负
	  lat: 39.456, //北纬为正，南纬为负
  },
  orgInfo: {
	 branch: '' 
  },
  province: "",
  city: "",
  country: "",
  address: "",   
  director: "",
  phone: "",
})
// 是否是编辑模式
const isEdit = ref(false)
onMounted(() => {
  console.log('加油站创建组织 onMounted')
  initUserInfo()
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const { type, data } = currentPage.options
  // 判断是否是编辑模式
  if (type === 'edit' && data) {
	  uni.setNavigationBarTitle({
	        title: '所属加油站' // 设定新标题
	  });
      isEdit.value = true
      try {
        // 解析传递的数据
        const decodedData = JSON.parse(decodeURIComponent(data))
  		
  	  // 使用对象展开运算符一次性赋值
  		formData.value = {
  			...formData.value,  // 保留原有的默认值
  			...decodedData
  		}
  		region.value.text = `${formData.value.province} ${formData.value.city} ${formData.value.country} `
  		console.log('更新后的表单数据:', JSON.stringify(formData.value, null, 2))
      } catch (error) {
        console.error('解析数据失败:', error)
      }
    } else {
		uni.setNavigationBarTitle({
		      title: '' // 设定新标题
		});
	}
})

// 页面显示时检查状态
onShow(() => {
  console.log("加油站创建组织 onShow")
  initUserInfo()
  getBrands()
})
// 初始化用户信息
const initUserInfo = () => {
  const storedInfo = userStore.getUserInfo()
  if (storedInfo) {
    formData.value.phone = userStore.getPhone()
	formData.value.director=  userStore.getRealName()
  }
}
	




// 品牌选择相关
const brandPopup = ref(null)
// 表单状态管理
const brands = ref([])
const currentBrandIndex = ref(0)
// 打开品牌选择器
const openBrandPicker = () => {
  brandPopup.value.open()
}
// 品牌选择器相关方法
const onBrandPickerChange = (e) => {
  currentBrandIndex.value = e.detail.value[0]
}

const confirmBrandSelect = () => {
  formData.value.orgInfo.branch = brands.value[currentBrandIndex.value]
  brandPopup.value.close()
}

const cancelBrandSelect = () => {
  brandPopup.value.close()
}




const region = ref({
	text: '',
	code: ''
})

// 添加省市区选择器相关代码
const regionPicker = ref(null)

// 打开地区选择器
const openRegionPicker = () => {
  regionPicker.value.open()
}

// 确认选择地区
const onRegionConfirm = (regionObj) => {
   console.log(JSON.stringify(regionObj))
  let regionList = regionObj.text.split(' ')
  if (regionList.length == 3) {
	 console.log(regionList[0])
	 console.log(regionList[1])
	 console.log(regionList[2])
	 formData.value.province = regionList[0]
	 formData.value.city = regionList[1]
	 formData.value.country = regionList[2]
	 region.value = regionObj
  }
}
// 取消选择地区
const onRegionCancel = () => {
  console.log('取消选择')
}



//更新用户信息
const getUserInfo = async() => {
	try {
		const result = await userApi.getUserInfo()
		if (result.code == undefined) {
		  return result
		} else {
		  throw new Error(result.msg || '获取用户信息失败')
		}
			   
	} catch (error){
	   uni.showToast({
		 title: error.message || '获取用户信息失败',
		 icon: 'none'
	   })
	}
}

// 获取品牌列表
const getBrands = async () => {
  try {
    const res = await orgApi.getBrandList()
    if(res.code == undefined) {
      brands.value = res
    } else {
      throw new Error(res.message || '获取品牌列表失败')
    }
  } catch(err) {
    uni.showToast({
      title: err.message || '获取品牌列表失败',
      icon: 'none'
    })
  } 
}

// 提交表单
const handleSubmit = async() => {
	isSubmit.value = true
  // 表单验证
  if (!formData.value.name) {

    uni.showToast({ title: '请填写加油站名称', icon: 'none' })
    return
  }
  if (!formData.value.fullname) {
    uni.showToast({ title: '请填写全称', icon: 'none' })
    return
  }
  if (!formData.value.orgInfo.branch) {
    uni.showToast({ title: '请选择品牌', icon: 'none' })
    return
  }
 
  if (!region.value) {
    uni.showToast({ title: '请选择省市区', icon: 'none' })
    return
  }
  if (!formData.value.address) {
    uni.showToast({ title: '请填写详细地址', icon: 'none' })
    return
  }
 
  try {
     const result = await await (isEdit.value ? 
	      orgApi.updateOrg(formData.value) : 
	      orgApi.createOrg(formData.value))
     if (result.code == undefined) {
	   let userResult = await getUserInfo()
	   showSuccessToast()
	  //  uni.showToast({
	  //    title: '创建成功',
	  //    icon: 'success',
		 // duration:1000
	  //  })
	   userStore.saveUserInfo(userResult)
	   setTimeout(()=>{
		  if(isEdit.value) {
			 Router.back()
		  } else {
			 RouterMethods.toGasCreateShare(result.id,true)  
		  }
	   },1300)
	   
     } else {
       throw new Error(result.msg || '提交失败')
     }
   } catch (error) {
     // uni.showToast({
     //   title: error.message || '提交失败',
     //   icon: 'none'
     // })
	 showErrorToast()
   }
  

  // console.log(result)
  // if (result) {
	 //  showSuccessToast()
  // } else {
	 //  showErrorToast()
  // }
 
}

// toast组件引用
const toastRef = ref(null)

// 自定义toast位置
const toastPosition = {
  bottom: 142 +'rpx',
  left: '58rpx',
  right: '58rpx',
}
// 显示成功提示
const showSuccessToast = () => {
  toastRef.value.showToast({
    text: '组织创建成功。',
    type: 'success',
    duration: 2000
  })
}

// 显示失败提示
const showErrorToast = () => {
  toastRef.value.showToast({
    text: '组织创建失败，请稍后重试或联系客服。',
    type: 'error',
    duration: 2000
  })
}

</script>

<style scoped>
.create-container {
  min-height: 100vh;
  background-color: #FFFFFF;
  padding: 0 56rpx;
  display: flex;
  flex-direction: column;
}

.scroll-area {
  overflow: hidden;
  padding-bottom: calc(82rpx + env(safe-area-inset-bottom) + 40rpx); /* 添加底部内边距，预留按钮高度空间 */
  z-index: 10
}

.role-container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.section-title {
  margin-top: 56rpx;
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
   width: 100%;
}
.form-section {
  background-color: #FFFFFF;
   width: 100%;
}

.base-form-item {
  display: flex;
  flex-direction: column;
  padding-top: 40rpx;
  border-bottom: 2rpx solid #001E32;
}

.base-form-item.active {
  border-bottom: 2rpx solid #BA0C2F;
}

.base-label-box {
  display: flex;
  align-items: center;
  margin-bottom: 26rpx;
}

.label {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}
.required {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #BA0C2F;
  letter-spacing: 0;
  font-weight: 500;
}

.fail-label {
	margin-left: 10rpx;
	font-family: PingFangSC-Medium;
	font-size: 24rpx;
	color: #BA0C2F;
	letter-spacing: 0;
	font-weight: 500;
}
.name-text {
	font-family: PingFangSC-Medium;
	font-size: 28rpx;
	color: #001E32;
	letter-spacing: 0;
	font-weight: 500;
	 margin-bottom: 8rpx;
}
.phone-text {
	font-family: PingFangSC-Medium;
	font-size: 28rpx;
	color: #001E32;
	letter-spacing: 0;
	font-weight: 500;
	 margin-bottom: 8rpx;
}

.input {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
   margin-bottom: 8rpx;
}

.picker-value {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 13rpx;
  
}
.placeholder {
    color: #B5B5B5;
}



.arrow {
  color: #001E32;
  font-size: 28rpx;
}

/* 选择器弹窗样式 */
.picker-content {
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 999;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  border-bottom: 2rpx solid #001E32;
}

.cancel-btn {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
}

.picker-title {
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.confirm-btn {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #3678BF;
  letter-spacing: 0;
  font-weight: 500;
}

.picker-view {
  width: 100%;
  height: 480rpx;
  z-index: 999;
}

.picker-item {
  line-height: 88rpx;
  text-align: center;
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
}

/* 底部按钮区域样式修改 */
.button-section {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #FFFFFF;
  z-index: 20
}

.surebutton {
  border-radius: 0;
}
</style>